<template>
  <div class="drawer-content">
    <div class="sections-grid">
      <div class="section-row">
        <!-- 饮食建议 -->
        <!-- 循环 dietSuggestionsArr，分别渲染“饮食运动建议”和“生活习惯建议” -->
        <div class="section">
          <div class="flex justify-between">
            <!-- 名字为2显示“饮食运动建议”，3显示“生活习惯建议” -->
            <div class="section-title">
              {{ t("healthRecords.advice.sections.dietExercise") }}
            </div>
          </div>

          <!-- AI 建议 -->
          <div v-if="dietSuggestions.length > 0" class="sub-section">
            <div class="sub-title">
              {{ t("healthRecords.advice.subsections.aiSuggestion") }}
            </div>
            <div
              v-for="item in dietSuggestions"
              :key="item.suggestionId"
              class="suggestion-item"
            >
              <div class="suggestion-content">
                <!-- <div>{{ item.aiTitle || "AI智能分析" }}</div> -->
                <div>
                  {{
                    item.content ||
                    t("healthRecords.advice.placeholders.noAiSuggestion")
                  }}
                </div>
              </div>
              <el-button type="primary" link @click="quoteAISuggestion(item)">
                {{ t("healthRecords.advice.buttons.quote") }}
              </el-button>
            </div>
          </div>

          <!-- 医生建议 -->
          <div class="sub-section">
            <div class="sub-title">
              {{ t("healthRecords.advice.subsections.doctorSuggestion") }}
            </div>
            <el-input
              v-model="doctorSuggestion"
              type="textarea"
              :rows="4"
              :placeholder="
                t('healthRecords.advice.placeholders.enterDoctorSuggestion')
              "
            />
          </div>
        </div>
        <!-- 用药建议 -->
        <div class="section">
          <div class="flex justify-between">
            <!-- 名字为2显示“饮食运动建议”，3显示“生活习惯建议” -->
            <div class="section-title">
              {{ t("healthRecords.advice.sections.medication") }}
            </div>
          </div>
          <el-table :data="medicationList" border>
            <el-table-column
              prop="drugName"
              :label="t('healthRecords.healthInfo.medicationTable.drugName')"
              width="200"
            >
              <template #default="{ row }">
                <el-input
                  v-model="row.drugName"
                  :placeholder="
                    t('healthRecords.healthInfo.placeholders.enterDrugName')
                  "
                  class="borderless-input"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="usageMethod"
              :label="t('healthRecords.healthInfo.medicationTable.usageMethod')"
              width="200"
            >
              <template #default="{ row }">
                <el-input
                  v-model="row.usageMethod"
                  :placeholder="
                    t('healthRecords.healthInfo.placeholders.enterUsage')
                  "
                  class="borderless-input"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="doseQuantity"
              :label="
                t('healthRecords.healthInfo.medicationTable.doseQuantity')
              "
              width="200"
            >
              <template #default="{ row }">
                <el-input
                  v-model="row.doseQuantity"
                  :placeholder="
                    t('healthRecords.healthInfo.placeholders.enterDose')
                  "
                  class="borderless-input"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="frequency"
              :label="t('healthRecords.healthInfo.medicationTable.doseUnit')"
              width="200"
            >
              <template #default="{ row }">
                <el-input
                  v-model="row.doseUnit"
                  :placeholder="
                    t('healthRecords.healthInfo.medicationTable.doseUnit')
                  "
                  class="borderless-input"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="frequency"
              :label="t('healthRecords.healthInfo.medicationTable.frequency')"
              width="200"
            >
              <template #default="{ row }">
                <el-input
                  v-model="row.frequency"
                  :placeholder="
                    t('healthRecords.healthInfo.placeholders.enterFrequency')
                  "
                  class="borderless-input"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="timing"
              :label="t('healthRecords.healthInfo.medicationTable.timing')"
              width="200"
            >
              <template #default="{ row }">
                <el-input
                  v-model="row.timing"
                  :placeholder="
                    t('healthRecords.healthInfo.placeholders.enterTiming')
                  "
                  class="borderless-input"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="treatment"
              :label="t('healthRecords.healthInfo.medicationTable.treatment')"
              width="200"
            >
              <template #default="{ row }">
                <el-input
                  v-model="row.treatment"
                  :placeholder="
                    t('healthRecords.healthInfo.placeholders.enterTreatment')
                  "
                  class="borderless-input"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="startDate"
              :label="t('healthRecords.healthInfo.medicationTable.startDate')"
              width="200"
            >
              <template #default="{ row, $index }">
                <el-input
                  v-model="row.startDate"
                  readonly
                  :placeholder="
                    t('healthRecords.healthInfo.placeholders.startDate')
                  "
                  class="borderless-input date-input-field"
                  @click="handleOpenDatePicker($index)"
                >
                  <template #suffix>
                    <el-icon
                      class="cursor-pointer text-gray-400 hover:text-blue-500"
                    >
                      <Calendar />
                    </el-icon>
                  </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              :label="t('healthRecords.healthInfo.medicationTable.actions')"
              fixed="right"
            >
              <template #default="{ $index }">
                <el-button type="danger" link @click="deleteMedication($index)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="add-medication">
            <el-button link @click="addMedication">
              <el-icon><Plus /></el-icon
              >{{ t("healthRecords.advice.buttons.add") }}
            </el-button>
          </div>
        </div>
      </div>
      <div class="section-row">
        <!-- 健康建议 -->
        <div class="section half-width">
          <div class="flex justify-between">
            <!-- 名字为2显示“饮食运动建议”，3显示“生活习惯建议” -->
            <div class="section-title">
              {{ t("healthRecords.advice.sections.lifestyle") }}
            </div>
          </div>

          <!-- AI 建议 -->
          <div v-if="habitSuggestions.length > 0" class="sub-section">
            <div class="sub-title">
              {{ t("healthRecords.advice.subsections.aiSuggestion") }}
            </div>
            <div
              v-for="item in habitSuggestions"
              :key="item.suggestionId"
              class="suggestion-item"
            >
              <div class="suggestion-content">
                <!-- <div>{{ item.aiTitle || "AI智能分析" }}</div> -->
                <div>
                  {{
                    item.content ||
                    t("healthRecords.advice.placeholders.noAiSuggestion")
                  }}
                </div>
              </div>
              <el-button type="primary" link @click="quoteAISuggestion(item)">
                {{ t("healthRecords.advice.buttons.quote") }}
              </el-button>
            </div>
          </div>

          <!-- 医生建议 -->
          <div class="sub-section">
            <div class="sub-title">
              {{ t("healthRecords.advice.subsections.doctorSuggestion") }}
            </div>
            <el-input
              v-model="doctorHealthSuggestion"
              type="textarea"
              :rows="4"
              :placeholder="
                t('healthRecords.advice.placeholders.enterDoctorSuggestion')
              "
            />
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="drawer-footer">
    <el-button @click="handleSave(1)">{{
      t("healthRecords.advice.buttons.saveDraft")
    }}</el-button>
    <el-button type="primary" @click="handleSave(2)">{{
      t("healthRecords.advice.buttons.submit")
    }}</el-button>
  </div>
  <el-dialog
    v-model="showDatePicker"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    destroy-on-close
    center
    :title="'选择用药开始时间'"
    class="no-header-dialog"
  >
    <div class="date-picker-content">
      <el-date-picker
        v-model="tempDate"
        type="date"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        class="w-full"
        :clearable="true"
        :editable="false"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleConfirmDatePicker">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reportApi } from "@/api/report-api";
import { Delete, Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { defineProps, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
// Props
interface Props {
  reportId: number;
  reportType?: number;
  requestSource?: number;
  isCreate?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  reportId: 0,
  requestSource: 0,
  isCreate: false
});
// 时间选择器弹窗相关状态
const showDatePicker = ref(false); // 控制日期选择器弹窗显示
const currentEditingIndex = ref(-1); // 当前正在编辑的用药记录索引
const tempDate = ref(""); // 临时保存选择的日期

// 国际化
const { t } = useI18n();

// 医生建议内容
const doctorSuggestion = ref("");
const doctorHealthSuggestion = ref("");

// 用药列表
const medicationList = ref([]);
const dietSuggestions = ref([]);
const habitSuggestions = ref([]);
// 打开日期选择器弹窗
const handleOpenDatePicker = (index: number) => {
  console.log("打开日期选择器弹窗", {
    用药记录索引: index,
    当前开始时间: medicationList.value[index]?.startDate
  });

  currentEditingIndex.value = index;
  tempDate.value = medicationList.value[index]?.startDate || "";
  showDatePicker.value = true;
};
// 确认日期选择
const handleConfirmDatePicker = () => {
  if (currentEditingIndex.value < 0 || !medicationList.value) {
    console.error("确认日期时出错：无效的编辑索引");
    ElMessage.error("操作失败：无效的用药记录");
    return;
  }

  const originalDate =
    medicationList.value[currentEditingIndex.value]?.startDate;

  console.log("确认日期选择", {
    编辑索引: currentEditingIndex.value,
    原始日期: originalDate,
    新选择日期: tempDate.value
  });

  // 更新用药记录的开始时间
  if (medicationList.value[currentEditingIndex.value]) {
    medicationList.value[currentEditingIndex.value].startDate = tempDate.value;

    console.log("日期更新成功", {
      更新后的日期: medicationList.value[currentEditingIndex.value].startDate,
      用药记录: medicationList.value[currentEditingIndex.value]
    });
  }

  // 关闭弹窗并重置状态
  showDatePicker.value = false;
  currentEditingIndex.value = -1;
  tempDate.value = "";
};

// 引用AI建议时，只保留最新一次的引用内容，覆盖原有内容
const quoteAISuggestion = item => {
  console.log(
    t("healthRecords.advice.messages.quotedAiSuggestion", {
      content: item.content || ""
    })
  );
  // 根据建议类型判断覆盖到哪个输入框
  if (item.type === 2) {
    // 饮食运动建议
    doctorSuggestion.value = item.content || "";
  } else if (item.type === 3) {
    // 生活习惯建议
    doctorHealthSuggestion.value = item.content || "";
  }
};

// 添加用药
const addMedication = () => {
  medicationList.value.push({
    drugName: "",
    usageMethod: "",
    doseQuantity: "",
    frequency: "",
    timing: "",
    treatment: "",
    dataType: 1
  });
};

// 删除用药
const deleteMedication = (index: number) => {
  medicationList.value.splice(index, 1);
};

// 保存操作
const handleSave = saveType => {
  // 整理所有建议数据
  const details = [];

  // 添加饮食运动建议
  if (doctorSuggestion.value) {
    details.push({
      type: 2,
      content: doctorSuggestion.value,
      referenceId: dietSuggestions.value?.[0]?.referenceId // 如果有引用AI建议，记录其ID
    });
  }

  // 添加生活习惯建议
  if (doctorHealthSuggestion.value) {
    details.push({
      type: 3,
      content: doctorHealthSuggestion.value,
      referenceId: habitSuggestions.value?.[0]?.referenceId // 如果有引用AI建议，记录其ID
    });
  }
  // 处理用药数据，将 startDate 转换为毫秒级时间戳
  const processedMedications = medicationList.value.map(medication => ({
    ...medication,
    // 将 startDate 转换为毫秒级时间戳，如果没有日期则为空字符串
    startDate: medication.startDate
      ? new Date(medication.startDate).getTime()
      : ""
  }));
  console.log("mujin", processedMedications);
  const data = {
    id: props.reportId, // TODO: 这里需要使用实际的reportId
    saveType: saveType, // 1: 草稿, 2: 提交
    type: props.reportType,
    requestSource: Number(props.requestSource), // 添加 requestSource 作为接口入参
    healthSuggestions: details,
    medications: processedMedications
  };

  // 调用保存接口
  reportApi
    .healthSuggestionSave(data)
    .then(res => {
      console.log("保存结果：", res);
      if (res.code === 0) {
        ElMessage.success(
          saveType === 1
            ? t("healthRecords.advice.messages.draftSaveSuccess")
            : t("healthRecords.advice.messages.submitSuccess")
        );
      } else {
        ElMessage.error(
          res.message || t("healthRecords.advice.messages.saveFailed")
        );
      }
    })
    .catch(err => {
      console.error("保存失败：", err);
      ElMessage.error(t("healthRecords.advice.messages.saveFailedRetry"));
    });
};

const handleHealthSuggestion = async (reportId, type) => {
  const params = {
    id: reportId,
    type: type
  };
  console.log("mujin", params);
  const res = await reportApi.healthSuggestionApi(params);
  let { medications, healthSuggestions, ...rest } = res.data;

  // 先按照type 2：饮食运动建议 3：生活习惯建议 分为两组 然后后价格字段name 分别为饮食运动建议 生活习惯建议
  let dietSuggestionsArr = healthSuggestions?.filter(item => item.type === 2);
  let habitSuggestionsArr = healthSuggestions?.filter(item => item.type === 3);

  dietSuggestions.value = dietSuggestionsArr?.filter(item => item.ai);
  habitSuggestions.value = habitSuggestionsArr?.filter(item => item.ai);
  doctorSuggestion.value = dietSuggestionsArr
    ?.filter(item => !item.ai)
    .map(item => item.content)
    .join(",");

  doctorHealthSuggestion.value = habitSuggestionsArr
    ?.filter(item => !item.ai)
    .map(item => item.content)
    .join(",");
};
onMounted(() => {
  if (!props.isCreate) {
    handleHealthSuggestion(props.reportId, props.reportType);
  }
});
</script>

<style scoped lang="scss">
.sections-grid {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.section-row {
  display: flex;
  gap: 20px;

  .section {
    flex: 1 1 0; // 强制等宽，忽略内容宽度
    min-width: 0; // 允许收缩到0
    &.half-width {
      flex: 0 0 calc(50% - 10px);
    }
  }
}
.section {
  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 16px;
    padding-left: 8px;
    border-left: 4px solid #409eff;
  }

  .sub-section {
    margin-bottom: 16px;

    .sub-title {
      font-size: 14px;
      color: #666;
      margin-bottom: 12px;
    }
  }
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 12px;

  .suggestion-content {
    flex: 1;

    div {
      &:first-child {
        font-weight: 500;
        margin-bottom: 4px;
      }

      &:last-child {
        color: #666;
        font-size: 14px;
      }
    }
  }
}

.add-medication {
  margin-top: 12px;
  display: flex;
  width: 68px;
  height: 28px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #d6d6d6;
  color: #333;
  flex-wrap: nowrap;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

:deep(.el-table) {
  margin-top: 12px;

  .el-button {
    padding: 4px 0;
  }
}

.drawer-footer {
  text-align: right;
  padding: 0 20px 20px;
}
// 日期输入框样式
:deep(.date-input-field) {
  .el-input__wrapper {
    cursor: pointer;

    &:hover {
      box-shadow: 0 0 0 1px
        var(--el-input-hover-border, var(--el-border-color-hover)) inset;
    }
  }

  .el-input__inner {
    cursor: pointer;
  }
}
.no-header-dialog {
  .el-dialog__body {
    text-align: center;
  }
}
</style>
